const config = require('./config')
App({
  globalData: {
  },
  onLaunch: function () {
    let self = this
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        const openIdUrl = config.openIdUrl
        wx.request({
          url: openIdUrl,
          data: {
            appId: config.appId,
            sCode: res.code
          },
          success: res => {
            if (res.data.openid) {
              // 存放openid到全局变量
              self.globalData.openid = res.data.openid
              // 防止请求还没响应之前，有页面用到了openid
              if (self.openIdReadyCallBack) {
                self.openIdReadyCallBack(self.globalData.openid)
              }
              
              // 获取用户信息 与OpenId一起发送给服务器 更新
              wx.getUserInfo({
                withCredentials: true,
                success: res => {
                  // 存放用户信息到全局变量
                  self.globalData.userInfo = res.userInfo
                  // 防止请求还没响应之前，有页面用到了userinfo
                  if (self.userInfoReadyCallback) {
                    self.userInfoReadyCallback(res)
                  }
                  let userInfo = res.userInfo
                  let nickName = userInfo.nickName
                  let avatarUrl = userInfo.avatarUrl
                  let gender = userInfo.gender //性别 0：未知、1：男、2：女
                  let province = userInfo.province
                  let city = userInfo.city
                  let country = userInfo.country
                  if (self.globalData.openid) {
                    wx.request({
                      url: config.gengXinXiaoChengXuYongHuUrl,
                      data: {
                        nickName: nickName,
                        avatarUrl: userInfo.avatarUrl,
                        gender: userInfo.gender, //性别 0：未知、1：男、2：女
                        province: userInfo.province,
                        city: userInfo.city,
                        country: userInfo.country,
                        openId: self.globalData.openid,
                      },
                      success: res => {
                        console.log('用户信息更新成功')
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            console.log('拉取用户openid失败，将无法正常使用开放接口等服务', res)
            //callback(res)
          }
        })
      },
      fail: function (err) {
        console.log('wx.login 接口调用失败，将无法正常使用开放接口等服务', err)
        //callback(err)
      }
    })

  }
});
